package com.baizhi.service.impl;

import com.baizhi.dao.CmfzAdminDao;
import com.baizhi.dao.CmfzAdminRoleDao;
import com.baizhi.dao.CmfzRoleDao;
import com.baizhi.entity.CmfzAdmin;
import com.baizhi.entity.CmfzAdminRole;
import com.baizhi.entity.CmfzRole;
import com.baizhi.service.CmfzAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by Administrator on 2019/4/20 0020.
 */
@Service
public class CmfzAdminServieImpl implements CmfzAdminService {
    @Autowired
    private CmfzAdminDao cmfzAdminDao;
    @Autowired
    private CmfzAdminRoleDao cmfzAdminRoleDao;
    @Autowired
    private CmfzRoleDao cmfzRoleDao;

    private Logger logger= LoggerFactory.getLogger(CmfzAdminServieImpl.class);


    @Override
    public Boolean regist(String adminUsername, String adminPassword) {
        try {
        /*生成一个盐值*/
            String salt = UUID.randomUUID().toString();

        /*生成密文*/
            Md5Hash md5Hash = new Md5Hash(adminPassword, salt, 1024);

            CmfzAdmin cmfzAdmin = new CmfzAdmin();
            cmfzAdmin.setAdminUsername(adminUsername);
            cmfzAdmin.setAdminPassword(md5Hash.toString());
            cmfzAdmin.setAdminSalt(salt);
            cmfzAdminDao.insert(cmfzAdmin);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public CmfzAdmin login(String adminUsername, String adminPassword) {
        /*将用户输入的账号密码封装到token中，给subject*/
        UsernamePasswordToken token = new UsernamePasswordToken(adminUsername,adminPassword);

        /*将从数据库中查到的数据给subject*/
        IniSecurityManagerFactory securityManagerFactory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager =  securityManagerFactory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        /*获取subject对象调用登录的方法*/
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);

            Map map = new HashMap();
            map.put("admin_username", adminUsername);
            List list= cmfzAdminDao.selectByMap(map);
            CmfzAdmin cmfzAdmin = (CmfzAdmin) list.get(0);
            logger.info("登录成功");
            return cmfzAdmin;
        }catch (IncorrectCredentialsException e){
            logger.info("密码错误");
            return null;
        }catch (UnknownAccountException e1){
            logger.info("账号不存在");
            return null;
        }
    }

    @Override
    public void logout(HttpSession session) {
        session.setAttribute("cmfzAdmin", null);
    }

    @Override
    public Map queryAll(Integer page, Integer rows) {
        Map map = new HashMap();

        IPage<CmfzAdmin> iPage = new Page<>(page, rows);
        IPage<CmfzAdmin> cmfzAdminIPage = cmfzAdminDao.selectPage(iPage, null);
        List<CmfzAdmin> records = cmfzAdminIPage.getRecords();

        for(CmfzAdmin cmfzAdmin:records){

            Integer adminId = cmfzAdmin.getAdminId();
            /*查中间表，根据admin_id获取角色信息*/
            List<CmfzAdminRole> cmfzAdminRoles = cmfzAdminRoleDao.selectList(new QueryWrapper<CmfzAdminRole>().eq("admin_id", adminId));
            ArrayList<Integer> roleIds = new ArrayList<>();
            for (CmfzAdminRole cmfzAdminRole : cmfzAdminRoles) {
                roleIds.add(cmfzAdminRole.getRoleId());
            }

        /*查role表，获取角色信息*/
            List<CmfzRole> cmfzRoles = cmfzRoleDao.selectList(new QueryWrapper<CmfzRole>().in("role_id", roleIds));
            cmfzAdmin.setCmfzRoles(cmfzRoles);
        }
        long total = cmfzAdminIPage.getTotal();

        map.put("total", total);
        map.put("rows", records);
        return map;
    }
}
